#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include <unistd.h>
#include <stdlib.h>
#include <signal.h>

void process_handler(){
    int i=0;
    printf("---server runing---\n");
    while(1){
        printf("--i(%d)--\n", i++);
        sleep(2);
    }
}

int main(int argc, char const *argv[])
{
    
    key_t k = ftok("/", 1); // 获取IPC的键值
    int shmid = shmget(k, 4, IPC_CREAT|0644);
    if(shmid == -1){
        perror("shmget");
        return -1;
    }
    pid_t pid=0;
    int *cmd = NULL;
    while(1){
        pid = fork();
        if(pid == 0){
            process_handler(); // 启动子进程的功能
        }

        // 读取指令： restart 1,  stop 2
        int *cmd = (int *)shmat(shmid, NULL, 0);
        if(cmd == NULL) break;

waitcmd:
        while(*cmd == 0) usleep(1000*100); // 死等指令

        if(*cmd == 1){
            kill(pid, SIGQUIT);
            wait(NULL);
            *cmd = 0;
        }else if(*cmd == 2){
            *cmd = 0;
            shmdt(cmd);  // 取消共享内存的映射
            break;
        }else{
            goto waitcmd;
        }
    }
    
    kill(0, SIGSTOP);
    wait(NULL);
    printf("--exit--\n");
   
    return 0;
}
